//
//  LoadingView.swift
//  svpro
//
//  Created by Nick xu on 16/7/26.
//  Copyright © 2016年 hddden. All rights reserved.
//

import UIKit

class LoadingView: UIView {
    
    var backLayer:CALayer?
    
    var cycleLayer:CALayer?
    
    static let shareLoadingView:LoadingView = {
        let view:LoadingView = LoadingView()
        view.frame = CGRect(x: 0, y: 0, width: KscreenWidth, height: KscreenHeight)
//        view.layer.contents = UIImage(named: "spinner_inner")?.CGImage
        let layerBg = CALayer()
        layerBg.backgroundColor = UIColor.clear.cgColor
        layerBg.frame = CGRect(x: KscreenWidth / 2 - 50, y: KscreenHeight / 2 - 75, width: 100, height: 100)
        layerBg.cornerRadius = 10
        view.layer.addSublayer(layerBg)
        let layerInner = CALayer()
        layerInner.frame = CGRect(x: KscreenWidth / 2 - 25, y: KscreenHeight / 2 - 50, width: 50, height: 50)
        layerInner.contents = UIImage(named: "spinner_inner")?.cgImage
        let layerOuter:CALayer = CALayer()
        layerOuter.frame = CGRect(x: KscreenWidth / 2 - 25, y: KscreenHeight / 2 - 50, width: 50, height: 50)
        layerOuter.contents = UIImage(named: "spinner_outer")?.cgImage
        view.layer.addSublayer(layerInner)
        view.layer.addSublayer(layerOuter)
        view.cycleLayer = layerOuter
        return view
    }()
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    class func  showLoading() {
        let window:UIWindow! = UIApplication.shared.delegate?.window!
        if self.shareLoadingView.superview == window {
            return
        }
        window.addSubview(self.shareLoadingView)
        if let textField = viewCacheManager.activedTextField(){
            textField.resignFirstResponder()
        }
    }
    class func dismissLoading() {
        UIView.animate(withDuration: 0.5, animations: {
            self.shareLoadingView.alpha = 0.3
        }, completion: { (true) in
            shareLoadingView.removeFromSuperview()
            self.shareLoadingView.alpha = 1
        }) 
    }
    //执行动画
    override func didMoveToWindow() {
        
        let caani:CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        caani.toValue = NSNumber(value: M_PI_2 * 4 as Double)
        caani.duration = 4
        caani.repeatCount = MAXFLOAT
        caani.isRemovedOnCompletion = false
        self.cycleLayer?.add(caani, forKey: "cycle")
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
